package com.tc.utils;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static String PostJson(String url, String json, int connectionTimeout, int soTimeout) throws Exception {
        StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
        return Post(url, connectionTimeout, soTimeout, stringEntity);
    }

    public static String PostJson(String url,  int connectionTimeout, int soTimeout) throws Exception {
        return Post(url, connectionTimeout, soTimeout, null);
    }
    
    public static String PostForm(String url, List<NameValuePair> nameValuePairList, int connectionTimeout, int soTimeout) throws Exception {
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
        return Post(url, connectionTimeout, soTimeout, urlEncodedFormEntity);
    }

    private static String Post(String url, int connectionTimeout, int soTimeout, HttpEntity httpEntity) throws Exception {
        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8"));
        headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
        headers.add(new BasicHeader(HttpHeaders.CONTENT_ENCODING, "utf-8"));

        HttpClient client = HttpClients.custom().setDefaultHeaders(headers).build();
        HttpPost post = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(soTimeout).setConnectTimeout(connectionTimeout).build();
        post.setConfig(requestConfig);

        InputStream input = null;//输入流
        InputStreamReader isr = null;
        BufferedReader buffer = null;
        StringBuilder sb = new StringBuilder();
        String line;
        try {
        	if(null != httpEntity)
            post.setEntity(httpEntity);
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //从服务器获得输入流
                input = res.getEntity().getContent();
                isr = new InputStreamReader(input, "UTF-8");
                buffer = new BufferedReader(isr, 10 * 1024);

                while ((line = buffer.readLine()) != null) {
                    sb.append(line);
                }
            } else {
                logger.error(url);
            }
        } finally {
            try {
                if (buffer != null) {
                    buffer.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (input != null) {
                    input.close();
                }
            } catch (Exception e) {
                logger.error("HttpClientUtil Post:", e);
            }
        }
        return sb.toString();
    }
    public static String Get(String url, Map<String,String> map) throws Exception {
        if(map !=null && !map.isEmpty()){
            for (Map.Entry<String, String> m : map.entrySet()) {
                url+="&"+m.getKey()+"="+m.getValue();
            }
        }
       // url=URLEncoder.encode(url);
        System.out.println(url);
        return Get(url, 2 * 60 * 1000, 2 * 60 * 1000);
    }

    public static String Get(String url, int connectionTimeout, int soTimeout) throws Exception {
        HttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(soTimeout).setConnectTimeout(connectionTimeout).build();
        httpGet.setConfig(requestConfig);

        InputStream input = null;//输入流
        InputStreamReader isr = null;
        BufferedReader buffer = null;
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            HttpResponse res = client.execute(httpGet);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //从服务器获得输入流
                input = res.getEntity().getContent();
                isr = new InputStreamReader(input, "UTF-8");
                buffer = new BufferedReader(isr, 10 * 1024);
                while ((line = buffer.readLine()) != null) {
                    sb.append(line);
                }
            } else {
                throw new Exception("http 响应异常:"+res);
            }
        } finally {
            try {
                if (buffer != null) {
                    buffer.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (input != null) {
                    input.close();
                }
            } catch (Exception e) {
                logger.error("HttpClientUtil Get:", e);
            }
        }
        return sb.toString();
    }
    private final static String ENCODE = "GBK";

}
